<?php
/*********************************************
 *  CPG Dragonfly™ CMS
 *********************************************
	Copyright © since 2010 by CPG-Nuke Dev Team
	http://dragonflycms.org

	Dragonfly is released under the terms and conditions
	of the GNU GPL version 2 or any later version
*/

namespace Poodle;

/* PHP 5.4: php.net/traits
trait Events
*/
abstract class Events implements \Poodle\Events_Interface
{
	protected
		$_poodle_events = array();

	public function addEventListener($type, $function)
	{
		$type = strtolower($type);
		if (!is_callable($function)) { trigger_error('Function for Event '.$type.' is not callable in '.get_class($this)); }
		else if (!isset($this->_poodle_events[$type])) { $this->_poodle_events[$type] = array($function); }
		else if (!in_array($function, $this->_poodle_events[$type], true)) { $this->_poodle_events[$type][] = $function; }
	}

	public function dispatchEvent(\Poodle\Events\Event $event)
	{
		$event->target = $this;
		$type = strtolower($event->type);
		if (!empty($this->_poodle_events[$type])) {
			foreach ($this->_poodle_events[$type] as $callback) { call_user_func($callback, $event); }
/*				try { call_user_func($callback, $event); }
				catch (\Exception $e) { \Poodle\LOG::error(__CLASS__, $e->getMessage()."\n".$e->getTraceAsString()); }*/
		}
//		else { trigger_error('Event type '.$type.' is empty in '.get_class($this)); }
	}

	public function removeEventListener($type, $function)
	{
		$type = strtolower($type);
		if (empty($this->_poodle_events[$type])) { trigger_error('Event type '.$type.' is empty in '.get_class($this)); }
		else {
			$key = array_search($function, $this->_poodle_events[$type], true);
			if (false !== $key) { unset($this->_poodle_events[$type][$key]); }
		}
	}

	public function triggerEvent($type)
	{
		$this->dispatchEvent(new \Poodle\Events\Event($type));
	}

	protected function removeAllEventListeners($type=null)
	{
		if ($type) unset($this->_poodle_events[strtolower($type)]);
		else $this->_poodle_events = array();
	}
}
